package com.hadoop.wordcount;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount4 {

	public static class WordMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
		IntWritable one=new IntWritable(1);
		Text word=new Text();
		
		@Override
		public void map(LongWritable key,Text value, Context context) throws IOException, InterruptedException{
			StringTokenizer izer=new StringTokenizer(value.toString());
			while(izer.hasMoreElements()){
				word.set(izer.nextToken());
				context.write(word, one);
			}
			
		}
	}
	
	public static class WordReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
		int sum=0;
		IntWritable result=new IntWritable(0);
		@Override
		public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException{
			for(IntWritable count:values){
				sum +=count.get();
			}
			result.set(sum);
			context.write(key, result);
		}
	}
	
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{
		Path outPutPath=new Path(args[1]);
		Configuration conf=new Configuration();
		FileSystem fs=FileSystem.get(conf);
		if(fs.exists(outPutPath)){
			fs.delete(outPutPath,true);
		}
		
		Job job=Job.getInstance(conf, "word count");
		
		job.setJarByClass(WordCount4.class);
		job.setMapperClass(WordMapper.class);
		job.setReducerClass(WordReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		//job.setNumReduceTasks(2);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, outPutPath);
		//NLineInputFormat.setNumLinesPerSplit(job, 20);
		System.out.print(job.waitForCompletion(true)?0:1);
	}
}
